package com.uflower.product.service.impl;

import com.uflower.common.to.SkuReductionTo;
import com.uflower.common.to.SpuBoundTo;
import com.uflower.common.to.es.SkuEsModel;
import com.uflower.product.entity.*;
import com.uflower.product.feign.SearchFeignService;
import com.uflower.product.service.*;
import com.uflower.product.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import com.uflower.product.entity.SkuInfoEntity;
import com.uflower.product.service.SkuInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.uflower.common.utils.PageUtils;
import com.uflower.common.utils.Query;

import com.uflower.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private ProductAttrValueService attrValueService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private SearchFeignService searchFeignService;
    @Autowired
    private SpuInfoService spuInfoService;
    @Override
    public ProductDetailVo getProductDetailVo(Long skuId) {
        ProductDetailVo productDetailVo = new ProductDetailVo();
        ProductDetailVo.SkuVo skuVo = new ProductDetailVo.SkuVo();
        //查询当前的sku信息 销售属性
        SkuInfoEntity skuInfo= skuInfoService.getById(skuId);
        BeanUtils.copyProperties(skuInfo,skuVo);
        List<String> skuSaleAttrValues = skuSaleAttrValueService.getSkuSaleAttrValues(skuId);
        skuVo.setAttrs(skuSaleAttrValues);
        //查询并设置spu信息
        Long spuId = skuInfo.getSpuId();
        SpuInfoDescEntity spuInfo = spuInfoDescService.getById(spuId);
        BeanUtils.copyProperties(spuInfo,productDetailVo);
        //设置sku images
        List<String> images =  spuImagesService.getBySpuId(spuId);
        skuVo.setSkuImages(images);
        productDetailVo.setSku(skuVo);


        SpuInfoEntity spuInfoEntity = this.baseMapper.selectById(spuId);
        BeanUtils.copyProperties(spuInfoEntity,productDetailVo);
        productDetailVo.setSpuId(spuId);
        
        //组合生成所有销售属性
        return productDetailVo;
    }
    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity sku = skuInfoService.getById(skuId);
        return  this.getById(sku.getSpuId());

    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        // 1 保存spu的基本信息  pf_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);
        //2  保存spu的描述信息 pf_spu_info_desc
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(spuInfoEntity.getId());// 从上面保存的spuInfoEntity数据里面获取
        descEntity.setDecript(String.join(",",decript));
        spuInfoDescService.saveSpuInfoDesc(descEntity);
        // 3 保存spu的图片集     pf_spu_images
        List<String> images= vo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(),images);
        // 4 保存spu的规格参数 pf_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr->{
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            productAttrValueEntity.setAttrId(attr.getAttrId());
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            productAttrValueEntity.setAttrName(attrEntity.getAttrName());
            productAttrValueEntity.setAttrValue(attr.getAttrValues());
            productAttrValueEntity.setQuickShow(attr.getShowDesc());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        attrValueService.saveProductAttr(collect);
        //5 保存spu的积分信息 sms_spu_bounds
        //Bounds bounds =vo.getBounds();
        //SpuBoundTo spuBoundTo = new SpuBoundTo();
        //BeanUtils.copyProperties(bounds,spuBoundTo);
        //spuBoundTo.setSpuId(spuInfoEntity.getId());
        //调用远程服务接口
        //couponFeignService.saveSpuBounds(spuBoundTo);
        // 6 保存当前spu对应的所有的sku的信息
        List<Skus> skus = vo.getSkus();
        if(skus != null && skus.size() > 0){
            skus.forEach(item->{
                // 获取默认图片
                String defaultImg = "";
                for (Images image : item.getImages()){
                    if (image.getDefaultImg() == 1){
                        defaultImg = image.getImgUrl();
                    }
                }
                // 6.1 sku的基本信息 pms_sku_info
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item,skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.saveSkuInfo(skuInfoEntity);
                // 6.2 sku的图片信息 pms_sku_images
                Long skuId = skuInfoEntity.getSkuId();
                List<SkuImagesEntity> imagesEntities = item.getImages().stream().map(img->{
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity->{
                    return StringUtils.isEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(imagesEntities);
                // 6.3 sku的销售属性信息 pms_sku_sale_attr_value
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(attr1->{
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr1,skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return   skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);
            });
        }
    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity infoEntity){
        this.baseMapper.insert(infoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and((w)->{
                w.eq("id",key).or().like("spu_name",key);
            });
        }

        String status = (String) params.get("status");
        if(!StringUtils.isEmpty(key)){
            wrapper.eq("publish_status",status);
        }

        String brandId = (String) params.get("brandId");
        if(!StringUtils.isEmpty(key) &&! "0".equalsIgnoreCase(brandId)){
            wrapper.eq("brand_id",brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if(!StringUtils.isEmpty(key) &&! "0".equalsIgnoreCase(catelogId)){
            wrapper.eq("catalog_id",catelogId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }


    @Override
    public void spuUp(Long spuId) {
        //封装上架商品
        List<SkuEsModel> skusToUp = new ArrayList<>();
        
        List<SkuInfoEntity> skus = skuInfoService.listBySpuId(spuId);
        
        //查询spu对应的规格属性
        List<ProductAttrValueEntity>  productAttrValues= productAttrValueService.getBySpuId(spuId);
        List<Long> selectableAttrId = attrService.getSelectableAttrId();
        HashSet<Long> idSet = new HashSet<>(selectableAttrId);
        List<SkuEsModel.AttrsEsModel> attrList = new ArrayList<>();
        productAttrValues.stream().filter(item->idSet.contains(item.getAttrId()))
                .forEach(item -> {
                    //拆分用;分隔的属性
                    String vals = item.getAttrValue();
                    List<String> val;
                    if(item.getAttrValue().contains(";")){
                       val = Arrays.asList(vals.split(";"));
                    }else{
                        val = new ArrayList<>();
                        val.add(vals);
                    }
                    for (String s : val) {
                        SkuEsModel.AttrsEsModel attrsEsModel = new SkuEsModel.AttrsEsModel(item.getAttrId(), item.getAttrName(),s);
                        attrList.add(attrsEsModel);
                    }
        });
        for (SkuInfoEntity sku : skus) {
           SkuEsModel model = new SkuEsModel();
            //设置sku信息
            BeanUtils.copyProperties(sku,model);
            model.setSkuTitle(sku.getSkuTitle());
            model.setSkuPrice(sku.getPrice());
            model.setSkuImg(sku.getSkuDefaultImg());
            //设置库存信息
            model.setHasStock(sku.getWareCount()!=0);
            //设置热度评分
            model.setHotScore(0L);
            //设置品牌信息
            BrandEntity brand = brandService.getById(sku.getBrandId());
            model.setBrandName(brand.getName());
            model.setBrandImg(brand.getLogo());
            //设置分类信息
            CategoryEntity category = categoryService.getById(sku.getCatalogId());
            model.setCatelogId(category.getCatId());
            model.setCatelogName(category.getName());
            //设置检索属性
            model.setAttrs(attrList);

            skusToUp.add(model);
        }

        //做不来 不会搞 es
        searchFeignService.statusUp(skusToUp);
    }

}